from langchain.agents import create_react_agent, AgentExecutor
from langchain_community.llms.tongyi import Tongyi
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool, Tool
from rest_framework.response import Response
from rest_framework.views import APIView

from home.models import History


# Create your views here.


def tool1(input):
    datas = History.objects.all().order_by("-created_at")[:3]
    # data1 = ''
    # for data in datas:
    #     data1 += data.content
    # return data1
    data = [data.content for data in datas]
    return data


@tool
def tool2(input):
    """
    曾咨询过类似产品，使用工具
    :param input:
    :return:
    """
    return "你好，我曾经问过类似产品，但没有找到合适的。"


template = '''请尽可能回答以下问题。您可以使用以下工具:

            {tools}

            使用以下格式:

            Question: the input question you must answer
            Thought: you should always think about what to do
            Action: the action to take, should be one of [{tool_names}]
            Action Input: the input to the action
            Observation: the result of the action
            ... (this Thought/Action/Action Input/Observation can repeat N times)
            Thought: I now know the final answer
            Final Answer: the final answer to the original input question

            Begin!

            Question: {input}
            Thought:{agent_scratchpad}'''

prompt = ChatPromptTemplate.from_template(template)
htool1 = Tool(func=tool1, name="tool1", description=" 回答关于新产品的提问。根据历史记录回答关于新产品的提问。")
tools = [htool1, tool2]


class HomeView(APIView):
    def get(self, request):
        agent = create_react_agent(
            tools=tools,
            llm=Tongyi(),
            prompt=prompt,
        )

        agent_executor = AgentExecutor(
            agent=agent,
            tools=tools,
            verbose=True,
        )
        # 小米15有什么优点
        res = agent_executor.invoke({"input": "小米15怎么样？"})
        print(res)
        return Response('ok')


















